package com.maodou.core.datastore.db

import com.maodou.core.datastore.db.dao.CacheDao
import com.maodou.core.datastore.db.table.CacheEntry
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types

/**
 * 列表缓存工具：以 key 存取任意类型的列表（通过 Moshi 序列化为 JSON）。
 */
class ListCacheStore(
    val dao: CacheDao,
    val moshi: Moshi,
) {
    suspend inline fun <reified T> putList(
        key: String,
        value: List<T>,
        ttlSeconds: Long? = null,
    ) {
        val type = Types.newParameterizedType(List::class.java, T::class.java)
        val adapter = moshi.adapter<List<T>>(type)
        val json = adapter.toJson(value)
        dao.upsert(CacheEntry(key = key, json = json, updatedAt = System.currentTimeMillis(), ttlSeconds = ttlSeconds))
    }

    suspend inline fun <reified T> getList(
        key: String,
        acceptExpired: Boolean = true,
    ): List<T>? {
        val entry = dao.get(key) ?: return null
        if (!acceptExpired && entry.ttlSeconds != null) {
            val expired = entry.updatedAt + entry.ttlSeconds * 1000 < System.currentTimeMillis()
            if (expired) return null
        }
        val type = Types.newParameterizedType(List::class.java, T::class.java)
        val adapter = moshi.adapter<List<T>>(type)
        return runCatching { adapter.fromJson(entry.json) }.getOrNull()
    }

    suspend fun delete(key: String) { dao.delete(key) }
    suspend fun clearExpired(nowMs: Long = System.currentTimeMillis()) = dao.clearExpired(nowMs)
    suspend fun clearAll() = dao.clearAll()
}